<template>
	<view>
		<view class="uni-header">
			<!-- <view class="uni-group hide-on-phone">
				<view class="uni-title">{{ $t('demo.table.title') }}</view>
			</view> -->
			<view class="uni-group">
				<!-- 输入框 -->
				<input class="uni-search" type="text" v-model="searchVal" @confirm="search"
					:placeholder="$t('common.placeholder.query')" />
				<!-- 搜索按钮 -->
				<button class="uni-button" type="default" size="mini"
					@click="search">{{ $t('common.button.search') }}</button>
				<!-- 添加按钮 -->
				<button class="uni-button" type="primary" size="mini"
					@tap="addDangerForm">{{ $t('common.button.add') }}</button>
				<!-- 导入Excel按钮 -->
				<button class="uni-button" type="primary" size="mini"
					@tap="importExcel">{{ $t('common.button.importExcel') }}</button>
				<!-- 导出Excel按钮 -->
				<button class="uni-button" type="primary" size="mini"
					@tap="exportExcel">{{ $t('common.button.exportExcel') }}</button>
				<!-- 全部导出按钮 -->
				<button class="uni-button" type="primary" size="mini"
					@tap="exportAll">{{ $t('common.button.exportAll') }}</button>
			</view>
		</view>
		<view class="uni-container">
			<!-- 表格组件 -->
			<uni-table :loading="loading" border stripe type="selection" :emptyText="$t('common.empty')"
				@selection-change="selectionChange">
				<uni-tr>
					<!-- 表头列 -->
					<uni-th width="100" align="center">编号</uni-th>
					<uni-th width="120" align="center">主责部门</uni-th>
					<uni-th width="160" align="center">危险源名称</uni-th>
					<uni-th width="120" align="center">审批状态</uni-th>
					<uni-th width="200" align="center">驳回理由</uni-th>
					<uni-th align="center">操作</uni-th>
				</uni-tr>
				<uni-tr v-for="(item, index) in tableData" :key="item.id">
					<!-- 表格数据列 -->
					<uni-td>{{ item.no }}</uni-td>
					<uni-td>{{ item.deptName }}</uni-td>
					<uni-td>
						<view class="name">{{ item.name }}</view>
					</uni-td>
					<uni-td>
						<view class="status"><uni-tag :text="formatStatus(item.status)"
								:type="getTagType(item.status)"></uni-tag></view>
					</uni-td>
					<uni-td>
						<view v-if="item.status === 2" class="reason">
							<text>{{ item.rejectReason }}</text>
						</view>
					</uni-td>
					<uni-td>
						<view class="uni-group">
							<!-- 查看详情按钮 -->
							<button v-if="item.status === 1" class="uni-button" size="mini" type="primary"
								@tap="reviewDangerDetail(item)">{{ $t('common.button.review') }}</button>

							<!-- 编辑按钮 -->
							<button v-if="item.status !== 1 && item.createUser === userId" class="uni-button"
								size="mini" type="primary" @tap="editDangerForm(item)">
								{{ $t('common.button.edit') }}
							</button>

							<!-- 删除按钮 -->
							<button v-if="item.createUser === userId" class="uni-button" size="mini" type="warn"
								@tap="delDangerItem(item)">
								{{ $t('common.button.delete') }}
							</button>

							<!-- 审批按钮 -->
							<button v-if="item.status !== 1" class="uni-button" size="mini" type="primary"
								@tap="approveDangerItem(item)">{{ $t('common.button.approve') }}</button>

							<!-- 驳回按钮 -->
							<button v-if="item.status === 0" class="uni-button" size="mini" type="warn"
								@tap="rejectDangerItem(item)">{{ $t('common.button.reject') }}</button>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>

			<view class="uni-pagination-box">
				<!-- 分页组件 -->
				<!-- <uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" @change="change" /> -->
				<page-pagination :total="total" :pageSize="pageSize" :currentPage="pageCurrent"
					:pageSizes="[10,50,100,200]" layout="total,first,prev,page,next,last,limit" :numAround="true"
					:showBorder="false" @change="change" @sizeChange="sizeChange"></page-pagination>
			</view>
		</view>
		<!-- #ifndef H5 -->
		<fix-window />
		<!-- #endif -->
	</view>
</template>

<script>
	import Config from '@/config'

	// 导出默认模块
	export default {
		// 数据属性
		data() {
			return {
				userId: '',
				// 搜索值
				searchVal: '',
				// 表格数据
				tableData: [],
				// 每页数据量
				pageSize: 10,
				// 当前页
				pageCurrent: 1,
				// 数据总量
				total: 0,
				// 加载状态
				loading: false,
				selectedIndexs: []
			}
		},
		computed: {
			// 多选处理
			selectedItems() {
				return this.selectedIndexs.map((i) => this.tableData[i])
			},
			selectedIds() {
				return this.selectedItems.map((_) => _.id)
			}
		},
		onLoad() {
			const loginRes = uni.getStorageSync('loginRes')
			this.userId = Number(loginRes.userId)
			// 获取第一页数据
			this.getData(1)
		},
		// 方法
		methods: {
			importExcel() {
				uni.chooseFile({
					count: 1,
					success: (res) => {
						console.log('chooseFile:', res)
						const file = res.tempFiles[0]
						const filePath = res.tempFilePaths[0]
						this.importDangerExcel(filePath, 'fileUpload', '/risk/importSource')
					}
				})
			},
			async importDangerExcel(...args) {
				console.log(args)
				try {
					const res = await uni.$uu.Api.uploadFile(args[0], args[1], args[2])
					console.log(res)
					if (res.code === 100) {
						this.getData(1)
					}
				} catch (e) {
					console.log(e)
				}
			},
			async exportAll() {
				const params = {}

				try {
					const res = await uni.$uu.Api.exportAllDangerExcel(params)
					console.log(res)
					if (res.code === 100) {
						const url = Config.host
						const download_url = `${url}${res.content}`
						const eLink = document.createElement('a')
						eLink.style.display = 'none'
						eLink.href = download_url
						eLink.setAttribute('download', '危险源数据导出') //设置下载属性 以及文件名
						document.body.appendChild(eLink)
						eLink.click()
						document.body.removeChild(eLink)
					}
				} catch (e) {
					console.log(e)
				}
			},
			async exportExcel() {
				if (this.selectedIds.length === 0) {
					uni.showToast({
						title: `请选择要导出的项`,
						icon: 'none'
					})
					return
				}

				const params = {
					ids: this.selectedIds
				}

				try {
					const res = await uni.$uu.Api.exportDangerExcel(params)
					console.log(res)
					if (res.code === 100) {
						const url = Config.host
						const download_url = `${url}${res.content}`
						const eLink = document.createElement('a')
						eLink.style.display = 'none'
						eLink.href = download_url
						eLink.setAttribute('download', '危险源数据导出') //设置下载属性 以及文件名
						document.body.appendChild(eLink)
						eLink.click()
						document.body.removeChild(eLink)
					}
				} catch (e) {
					console.log(e)
				}
			},
			addDangerForm() {
				const url = `/pages/danger/edit/index?type=add`
				uni.navigateTo({
					url
				})
			},
			editDangerForm({
				id,
				status
			}) {
				const url = `/pages/danger/edit/index?type=edit&id=${id}&status=${status}`
				uni.navigateTo({
					url
				})
			},
			reviewDangerDetail({
				id,
				status
			}) {
				const url = `/pages/danger/edit/index?type=edit&id=${id}&status=${status}`
				uni.navigateTo({
					url
				})
			},
			delDangerItem({
				id
			}) {
				uni.showModal({
					title: '删除危险源',
					content: '确定要删除当前项吗?',
					success: (res) => {
						if (res.confirm) {
							this.delDanger(id)
						}
					}
				})
			},
			async delDanger(id) {
				const params = {
					id
				}

				try {
					const res = await uni.$uu.Api.delDanger(params)
					console.log(res)
					if (res.code === 100) {
						uni.showToast({
							title: '删除成功',
							success: () => {
								this.getData(1)
							}
						})
					}
				} catch (e) {
					console.log(e)
				}
			},
			approveDangerItem({
				id
			}) {
				uni.showModal({
					title: '审批危险源',
					content: '确定要审批当前项吗?',
					success: (res) => {
						if (res.confirm) {
							this.auditDanger(id)
						}
					}
				})
			},
			async auditDanger(id, content = '') {
				const params = {
					id
				}

				if (content !== '') {
					params['rejectReason'] = content
				}

				try {
					const res = await uni.$uu.Api.auditDanger(params)
					console.log(res)
					if (res.code === 100) {
						const title = content === '' ? '审批成功' : '驳回成功'
						uni.showToast({
							title,
							success: () => {
								this.getData(1)
							}
						})
					}
				} catch (e) {
					console.log(e)
				}
			},
			rejectDangerItem({
				id
			}) {
				uni.showModal({
					title: '驳回危险源',
					editable: true,
					placeholderText: '请输入要驳回的理由',
					success: (res) => {
						if (res.confirm) {
							console.log('rejectDangerItem: ', res.content)
							this.auditDanger(id, res.content) //editable 为 true 时，用户输入的文本
						}
					}
				})
			},
			getTagType(status) {
				const tagMap = {
					0: 'default',
					1: 'success',
					2: 'error'
				}
				return tagMap[status]
			},
			formatStatus(status) {
				const statusMap = {
					0: '未审批',
					1: '已审批',
					2: '已驳回'
				}
				return statusMap[status]
			},
			// 多选事件处理函数
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			// 批量删除函数
			delTable() {
				this.selectedItems()
			},
			change(e, type) {
				this.selectedIndexs = []
				this.pageCurrent = e;
				this.getData(e)
			},
			sizeChange(e) {
				console.log("sizeChange: ", e)
				this.pageSize = e;
				this.getData(this.pageCurrent)
			},
			// 搜索函数
			search() {
				this.getData(1, this.searchVal)
			},
			// 获取数据函数
			async getData(pageCurrent, value = '') {
				this.loading = true
				this.pageCurrent = pageCurrent

				const params = {
					page: this.pageCurrent,
					size: this.pageSize,
					name: value,
					type: 1 //获取列表的类型，1标识上报列表，0标识公示列表
				}

				try {
					const res = await uni.$uu.Api.getDangerList(params)
					console.log(res)
					if (res.code === 100) {
						this.total = res.count || 100
						this.tableData = [...res.content]
						this.loading = false
					}
				} catch (e) {
					console.log(e)
				}
			},
			// 伪request请求函数
			request(options) {
				const {
					pageSize,
					pageCurrent,
					success,
					value
				} = options

				let total = tableData.length

				let data = tableData.filter((item, index) => {
					const idx = index - (pageCurrent - 1) * pageSize
					return idx < pageSize && idx >= 0
				})

				if (value) {
					data = []
					tableData.forEach((item) => {
						if (item.danger_name.indexOf(value) !== -1) {
							data.push(item)
						}
					})
					total = data.length
				}

				setTimeout(() => {
					typeof success === 'function' &&
						success({
							data: data,
							total: total
						})
				}, 500)
			}
		}
	}
</script>

<style>
	/* #ifndef H5 */
	page {
		padding-top: 85px;
	}

	/* #endif */

	.uni-pagination-box {
		display: flex;
		align-items: center;


	}
</style>